<?php

namespace Common\Logic;

/**
 * Description of 酒店申请开通业务逻辑层
 * 
 * @author songanwei
 * @date 2015-12-31
 */
class HotelApplyLogic extends \Common\Controller\BaseController {

    /**
     * 用户提交客栈申请
     * @modify songanwei 2015-12-31 
     * @modify zhangzhen 2017-1-5 
     * @modify zhangzhen 2017-05-11 添加时区 区号
     * @param string $hotelName
     * @param string $cityName
     * @param string $mobile
     * @param string $userName
     * @param string $dealerId  申请来源
     * @param int $universalTimeId  时区 Id
     * @param int $countryId  国家id
     * @param int $areaCode  区号
     */
    public function apply($hotelName, $cityName, $mobile, $userName, $dealerId=0, $from, $universalTimeId = '5', $areaCode = '86', $countryId = null) {
        //检查手机号是否已经存在
        if ($this->checkMobile($mobile, $areaCode)) {
             returnJson(403, 405);
        }
        $hotelApplyModel = D('HotelApply');
        $result = $hotelApplyModel->addInfo($hotelName, $cityName, $mobile, $userName, $dealerId, $from, $universalTimeId, $areaCode, $countryId);
        if (!$result) {
            returnJson(500, 508);
        }
        //发送邮件通知
        $email = new \Org\Util\Email();
        if ($dealerId) {
            foreach (C('SIGNIN_NOTIFICATION_EMAIL') as $emailToSend) {
                $email->dealerApplyHotel($emailToSend, $hotelName, $mobile, $cityName, $userName);
            }
        } else {
            foreach (C('SIGNIN_NOTIFICATION_EMAIL') as $emailToSend) {
                $email->applyHotel($emailToSend, $hotelName, $mobile, $cityName, $userName, $from);
            }
        }

        unset($emailToSend);
    }
    /**
     * 经销商修改客栈申请
     * @modify zhangzhen 2017-1-6
     * @param string $applyId
     * @param string $hotelName
     * @param string $cityName
     * @param string $mobile
     * @param string $userName
     * @param string $dealerId  申请来源
     */
    public function updateApply($applyId, $hotelName, $cityName, $mobile, $userName) {
        $hotelApplyModel = D('HotelApply');
        $result = $hotelApplyModel->saveInfo($applyId, $hotelName, $cityName, $mobile, $userName);
        if (!$result) {
            returnJson(500, 508);
        }
        //发送邮件通知
        $email = new \Org\Util\Email();
        if ($dealerId) {
            foreach (C('SIGNIN_NOTIFICATION_EMAIL') as $emailToSend) {
                $email->dealerApplyHotel($emailToSend, $hotelName, $mobile, $cityName, $userName);
            }
        } else {
            foreach (C('SIGNIN_NOTIFICATION_EMAIL') as $emailToSend) {
                $email->applyHotel($emailToSend, $hotelName, $mobile, $cityName, $userName);
            }
        }
        unset($emailToSend);
    }
    /**
     * 检查手机号是否存在
     * @param  string $mobile 手机号
     * @return array         查询结果
     */
    public function checkMobile($mobile, $areaCode = '86') {
        $hotelApplyModel = D('HotelApply');
        $hotelApply = $hotelApplyModel->getInfoByMobile($mobile, $areaCode);
        if ($hotelApply) {
            return $hotelApply; 
        }
        $adminLoginModel = D('AdminLogin');
        $adminLogin = $adminLoginModel->getInfoByMobile($mobile, $areaCode);
        $adminHotelModel = D('AdminHotel');
        $result = $adminHotelModel->getInfosByAdmin($adminLogin['id']);
        return $result;
    }

    /**
     * 添加申请客栈(义卖客栈)
     * 2017-09-11 wenhui 创建 
     * @param  string $mobile 手机号
     * @return array         查询结果
     */
    public function addApplyHotel($hotelName, $cityName, $mobile, $userName, $universalTimeId = '5', $areaCode = '86', $countryId = null, $cityId = null, $districtId = null, $currencyId = null) {
        //检查手机号是否已经存在
        if ($this->checkMobile($mobile, $areaCode)) {
             returnJson(403, 405);
        }
        $dealerId = getDealerId();

        //检查用户是否已注册
        $adminLoginModel = D('AdminLogin');
        $adminHotelModel = D('AdminHotel');
        $hotelEntityModel = D('HotelEntity');
        $adminLogin = $adminLoginModel->getInfoByMobile($mobile, $areaCode);

        if ($adminLogin) {
            //检查用户是否已存在此客栈
            $adminHotels = $adminHotelModel->getInfosByAdmin($adminLogin['id']);
            foreach ($adminHotels as $adminHotel) {
                $hotelNameResult = $hotelEntityModel->getName($adminHotel['hotelentity_id']);
                if ($hotelNameResult == $hotelName) {
                    returnJson(403, 420);
                }
            }
        }

        //查询后端默认客栈支付方式、渠道数据
        $payModel = D('Pay');
        $channelModel = D('Channel');
        $noteModel = D('Note');

        $pays = $payModel->getAll();
        $channels = $channelModel->getAll();
        $notes = $noteModel->getAll();

        //开启事务处理
        $hotelEntityModel->startTrans();
        $commit = true;
        //添加客栈数据
        $result = $hotelId = $hotelEntityModel->addInfo($hotelName, $cityId, $districtId, null, 4, null, $universalTimeId);
        if ($result == false) {
            $commit = false;
        }

        // 添加客栈默认货币
        if ($commit && !is_null($currencyId)) {
            $currencyHotelModel = D('CurrencyHotel');
            $addResult = $currencyHotelModel->addDefaultCurrency($hotelId, $currencyId, 1);
            if ($addResult == false) {
                $commit = false;
            }
        }

        // 添加客栈信息记录
        if ($commit) {
            $hotelInfoModel = D('HotelInfo');
            $addResult = $hotelInfoModel->addInfo($hotelId);
            if (empty($addResult)) {
                $commit = false;
            }
        }

        //添加客栈支付方式
        if ($commit && $pays) {
            $hotelPayModel = D('HotelPay');
            foreach ($pays as $pay) {
                $hotelPayData[] = array(
                    'hotelentity_id' => $hotelId,
                    'name' => $pay['name'],
                    'type' => 1
                );
            }
            unset($pay);
            $result = $hotelPayModel->addAll($hotelPayData);
            if ($result == false) {
                $commit = false;
            }
        }

        //添加客栈默认渠道数据
        if ($commit && $channels) {
            $hotelChannelModel = D('HotelChannel');
            foreach ($channels as $channel) {
                $hotelChannelData[] = array(
                    'hotelentity_id' => $hotelId,
                    'name' => $channel['name'],
                    'type' => 1
                );
            }
            unset($channel);
            $result = $hotelChannelModel->addAll($hotelChannelData);
            if ($result == false) {
                $commit = false;
            }
        }

        //添加客栈记一笔项目
        if ($commit && $notes) {
            $hotelNoteModel = D('HotelNote');
            foreach ($notes as $note) {
                $hotelNoteData[] = array(
                    'hotelentity_id' => $hotelId,
                    'name' => $note['name'],
                    'type' => $note['type'],
                );
            }
            unset($note);
            $result = $hotelNoteModel->addAll($hotelNoteData);
            if ($result == false) {
                $commit = false;
            }
        }

        if ($adminLogin) {
            if($commit && $dealerId){
                $result = $adminLoginModel->saveInfo($adminLogin['id'],
                        array(
                            'status' => 4,
                        )
                    );
          
                if ($result == false) {
                    $commit = false;
                }  
            }

            //添加账号、客栈关系数据
            if ($commit) {
                $result = $adminHotelModel->addInfo($hotelId, $adminLogin['id'], 1);
                if ($result == false) {
                    $commit = false;
                }
            }

            //添加账号、经销商关系数据
            if ($commit && $dealerId) {
                $dealerAdminModel = D('DealerAdmin');
                $result = $dealerAdminModel->addInfo($dealerId, $adminLogin['id']);
                if ($result == false) {
                    $commit = false;
                }
            }
           
            if ($commit) {
                $hotelEntityModel->commit();
            } else {
                $hotelEntityModel->rollback();
                returnJson(500, 508);
            }
        } else {
            //未注册用户
            $password = getRandomPassword();
            $hotelEntityModel->startTrans();
            $commit = true;
            //添加主账号
            $result = $userId = $adminLoginModel->addInfo($mobile, hash('sha256', $password), $userName, $areaCode);
            if ($result == false) {
                $commit = false;
            }

            if($commit && $dealerId){
                $result = $adminLoginModel->saveInfo($userId,
                        array(
                            'status' => 4,
                        )
                    );
          
                if ($result == false) {
                    $commit = false;
                }  
            }
            
            //添加账号、经销商关系数据
            if ($commit  && $dealerId) {
                $dealerAdminModel = D('DealerAdmin');
                $result = $dealerAdminModel->addInfo($dealerId, $userId);
                if ($result == false) {
                    $commit = false;
                }
            }
            
            //添加账号、客栈关系数据
            if ($commit) {
                $result = $adminHotelModel->addInfo($hotelId, $userId, 1);
                if ($result == false) {
                    $commit = false;
                }
            }

            if ($commit) {
                $adminInfoModel = D('AdminInfo');
                $result = $adminInfoModel->addInfo($userId);
                if ($result == false) {
                    $commit = false;
                }
            }
            if ($commit) {
                $hotelEntityModel->commit();
                //发送未注册短信通知
                if ($areaCode == '86') {
                    $sms = new \Org\Util\Sms();
                    $sms->sendNotReg($mobile, $password);
                } else {
                    $sms = new \Org\Util\yunPian();
                    $sms->sendNotReg($areaCode, $mobile, $password);
                }
            } else {
                $hotelEntityModel->rollback();
                returnJson(500, 508);
            }
        }
    }

    /**
     * 添加义卖客栈
     * 2017-09-11 wenhui 创建 
     * @param  string $mobile 手机号
     * @return array         查询结果
     */
    public function addCharityHotel($hotelName, $universalTimeId = '5', $cityId = null, $districtId = null, $currencyId = null) {
        //检查用户是否已注册
        $adminHotelModel = D('AdminHotel');
        $hotelEntityModel = D('HotelEntity');
        $userId = getUserId();

        //检查用户是否已存在此客栈
        $adminHotels = $adminHotelModel->getInfosByAdmin($userId);
        foreach ($adminHotels as $adminHotel) {
            $hotelResult = $hotelEntityModel->getInfo($adminHotel['hotelentity_id']);
            if ($hotelResult['name'] == $hotelName) {
                returnJson(403, 420);
            }
            //检查用户是否已存在义卖客栈
            if ($hotelResult['usage'] == 4) {
                returnJson(403, 424);
            }
        }

        //查询后端默认客栈支付方式、渠道数据
        $payModel = D('Pay');
        $channelModel = D('Channel');

        $pays = $payModel->getAll();
        $channels = $channelModel->getAll();

        //开启事务处理
        $hotelEntityModel->startTrans();
        $commit = true;
        //添加客栈数据
        $result = $hotelId = $hotelEntityModel->addInfo($hotelName, $cityId, $districtId, null, 4, null, $universalTimeId);
        if ($result == false) {
            $commit = false;
        }

        // 添加客栈默认货币
        if ($commit && !is_null($currencyId)) {
            $currencyHotelModel = D('CurrencyHotel');
            $addResult = $currencyHotelModel->addDefaultCurrency($hotelId, $currencyId, 1);
            if ($addResult == false) {
                $commit = false;
            }
        }

        // 添加客栈信息记录
        if ($commit) {
            $hotelInfoModel = D('HotelInfo');
            $addResult = $hotelInfoModel->addInfo($hotelId);
            if (empty($addResult)) {
                $commit = false;
            }
        }

        //添加客栈支付方式
        if ($commit && $pays) {
            $hotelPayModel = D('HotelPay');
            foreach ($pays as $pay) {
                $hotelPayData[] = array(
                    'hotelentity_id' => $hotelId,
                    'name' => $pay['name'],
                    'type' => 1
                );
            }
            unset($pay);
            $result = $hotelPayModel->addAll($hotelPayData);
            if ($result == false) {
                $commit = false;
            }
        }

        //添加客栈默认渠道数据
        if ($commit && $channels) {
            $hotelChannelModel = D('HotelChannel');
            foreach ($channels as $channel) {
                $hotelChannelData[] = array(
                    'hotelentity_id' => $hotelId,
                    'name' => $channel['name'],
                    'type' => 1
                );
            }
            unset($channel);
            $result = $hotelChannelModel->addAll($hotelChannelData);
            if ($result == false) {
                $commit = false;
            }
        }
        //添加账号、客栈关系数据
        if ($commit) {
            $result = $adminHotelModel->addInfo($hotelId, $userId, 1);
            if ($result == false) {
                $commit = false;
            }
        }

        //会员设置为共享时，添加会员信息
        if($commit){
            $vipInitModel = D('VipInit');
            $vipInitInfo = $vipInitModel->getInfoByAdmin($userId);
            if($vipInitInfo['share'] == '1'){
                $adminHotelInfos = $adminHotelModel->getInfosByAdmin($userId);
                $vipInfoModel = D('VipInfo');
                $vipInfos = $vipInfoModel->getInfoByHotel($adminHotelInfos[0]['hotelentity_id']);
                foreach ($vipInfos as $key => $vipInfo) {
                    $addResult = $vipInfoModel->addInfo($vipInfo['name'], $hotelId, $vipInfo['auto'], $vipInitInfo['level'], $vipInfo['levelrule'], $vipInitInfo['discount'], $vipInfo['discountrule']);
                    if (!$addResult) {
                        $commit = false;
                        break;
                    }
                }
                if ($commit) {
                    $vipUserModel = D('VipUser');
                    $vipUserInfoModel = D('VipUserInfo');
                    $vipUsers = $vipUserModel->getInfoByHotel($adminHotelInfos[0]['hotelentity_id']);
                    foreach ($vipUsers as $key => $vipUser) {
                        $addResult = $vipUserModel->addInfo($hotelId, $vipUser['vipinfo_id'], $vipUser['name'], $vipUser['mobile'], $vipUser['identity'], $vipUser['areacode']);
                        $vipUserInfo = $vipUserInfoModel->getInfoByUserId($vipUser['id']);
                        $addResult=$vipUserInfoModel->addInfo($addResult,$vipUserInfo['gender'],$vipUserInfo['birthday'],$vipUserInfo['nation'],$vipUserInfo['address'],$vipUserInfo['wechat'],$vipUserInfo['remark']);
                        if (!$addResult) {
                            $commit = false;
                            break;
                        }
                    }
                }
            }
        }
       
        if ($commit) {
            $hotelEntityModel->commit();
        } else {
            $hotelEntityModel->rollback();
            returnJson(500, 508);
        }       
    }
}
